package disruptor;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.WorkHandler;
import netty.util.TimeDelay;

import java.nio.ByteBuffer;

class LongEvent {
    private long value;

    public void set(long value)
    {
        this.value = value;
    }
    public long getValue()
    {
        return this.value;
    }
}

class LongEventHandler implements EventHandler<LongEvent> {
    TimeDelay timeDelay = TimeDelay.getInstance();

    long sleep = 0;

    public LongEventHandler(long sleep) {
        this.sleep = sleep;
    }

    public LongEventHandler() {
    }

    public void onEvent(LongEvent event, long sequence, boolean endOfBatch) throws Exception {
        timeDelay.analyze(event.getValue());

        if (sleep != 0) {
            Thread.sleep(sleep);
        }
    }
}

class LongWorkHandler implements WorkHandler<LongEvent> {
    TimeDelay timeDelay = TimeDelay.getInstance();

    long sleep = 0;

    public LongWorkHandler(long sleep) {
        this.sleep = sleep;
    }

    public LongWorkHandler() {
    }

    public void onEvent(LongEvent event) throws Exception {
        timeDelay.analyze(event.getValue());

        if (sleep != 0) {
            Thread.sleep(sleep);
        }
    }
}

class LongEventFactory implements EventFactory<LongEvent> {
    public LongEvent newInstance() {
        return new LongEvent();
    }
}

class LongEventProducer {
    private final RingBuffer<LongEvent> ringBuffer;
    public LongEventProducer(RingBuffer<LongEvent> ringBuffer)
    {
        this.ringBuffer = ringBuffer;
    }

    public void onData(ByteBuffer bb)
    {
        try {
            long sequence = ringBuffer.next();  // Grab the next sequence
            try
            {
                LongEvent event = ringBuffer.get(sequence); // Get the entry in the Disruptor
                // for the sequence
                event.set(bb.getLong(0));  // Fill with data
            }
            finally
            {
                ringBuffer.publish(sequence);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}